package design.mode.dispatcher.util.groovydemo;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExcelSingleSheetEvaluator {
    private static final Pattern GROOVY_EXPRESSION_PATTERN = Pattern.compile("\\$\\{(.+?)\\}");

    public static void main(String[] args) {
        String path ="D:\\download\\report.xlsx";
        try {
            FileInputStream file = new FileInputStream(path);
            Workbook workbook = new XSSFWorkbook(file);

            // 获取唯一的工作表
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                for (Cell cell : row) {
                    String cellValue = cell.getStringCellValue();
                    Matcher matcher = GROOVY_EXPRESSION_PATTERN.matcher(cellValue);
                    if (matcher.find()) {
                        String groovyExpression = matcher.group(1);
                        String templateType = extractTemplateType(groovyExpression);
                        FillStrategy fillStrategy = getFillStrategy(templateType);
                        Object result = fillStrategy.process(cell,groovyExpression);
                        cell.setCellValue(result.toString());
                    }
                }
            }

            FileOutputStream outputStream = new FileOutputStream(path);
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String extractTemplateType(String expression) {
        // 提取模板类型，例如从"${report.getName()}"中提取"report"
        return expression.split("\\.")[0];
    }

    private static FillStrategy getFillStrategy(String templateType) {
        switch (templateType) {
            case "bean":
                return new ReportFillStrategy();
            default:
                throw new IllegalArgumentException("Unsupported template type: " + templateType);
        }
    }
}